package com.atguigu.tran;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Arrays;
import java.util.List;

/**
 * @author yhm
 * @create 2024-04-02 9:57
 */
public class Test02_Filter {
    public static void main(String[] args) throws Exception {
        // 1. 创建环境
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",8081);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // 2. 读取数据源
        List<WaterSensor> waterSensors = Arrays.asList(new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_2", 2000L, 20),
                new WaterSensor("sensor_3", 3000L, 30),
                new WaterSensor("sensor_4", 4000L, 40)
        );
        DataStreamSource<WaterSensor> dataStreamSource = env.fromCollection(waterSensors);

        // 3. 处理数据
        // 匿名子类
        SingleOutputStreamOperator<WaterSensor> streamOperator = dataStreamSource.filter(new FilterFunction<WaterSensor>() {
            @Override
            public boolean filter(WaterSensor value) throws Exception {
                if ("sensor_1".equals(value.id)) {
                    return true;
                }
                return false;
            }
        });
        // lambda表达式(匿名函数)
        SingleOutputStreamOperator<WaterSensor> streamOperator1 = dataStreamSource.filter(waterSensor -> "sensor_1".equals(waterSensor.id));

        SingleOutputStreamOperator<WaterSensor> streamOperator2 = dataStreamSource.filter(new CustomFilterFunction());

        // 4. 输出
        streamOperator2.print();

        // 5. 执行环境
        env.execute();
    }

    public static class CustomFilterFunction implements FilterFunction<WaterSensor>{

        @Override
        public boolean filter(WaterSensor value) throws Exception {
            return "sensor_1".equals(value.id);
        }
    }

}
